<?php
/**
* A container for managing user preferences.
*
* Copyright (c) 2009 James Gauld <james@jamesgauld.net>
* This file is part of Scribble.
* @license http://www.scribblecms.co.uk/license.txt
*
* @package Scribble
*/
class ScribbleUserPreferences {

	private $user;

	public function __construct($user) {
		$this->user = $user;
	}

	/**
	* Return a specific preference of $this user's. If there is no defined value
	* for the specified preference then return either the default, or NULL if no
	* default can be found.
	*
	* @param string Preference variable name
	* @return mixed
	*/
	public function get($pref) {
		$prefs = $this->user->prefs!='' ? json_decode($this->user->prefs) : new StdClass();
		return isset($prefs->{$pref}) ? $prefs->{$pref} : $this->getDefault($pref);
	}

	/**
	* Return an object containing all preferences.
	*
	* @return StdClass
	*/
	public function getAll() {
		$prefs = $this->user->prefs!='' ? json_decode($this->user->prefs) : new StdClass();
		return $prefs;
	}

	/**
	* Return the default value for the specified preference
	*
	* @param string Preference variable name
	* @return mixed
	*/
	public function getDefault($pref) {
		switch($pref) {
			case 'adminLanguage':
				return 'en';
			default:
				return NULL;
		}
	}

	/**
	* Set a preference, in both $this object and the associated user's "prefs"
	* field.
	*
	* @param string Preference variable name
	* @param mixed Preference value
	* @return void
	*/
	public function set($pref, $val) {

		$prefs = $this->user->prefs!='' ? json_decode($this->user->prefs) : new StdClass();
		$prefs->{$pref} = $val;
		$this->user->prefs = json_encode($prefs);
	}

	/**
	* Pass all defined preferences through a validator to determine if the
	* values are valid or not.
	*
	* @return bool
	*/
	public function validate() {
		return TRUE;
	}
}
?>